package com.hm.oauth.auto;

import java.io.IOException;
import java.io.PrintWriter;
import java.net.HttpURLConnection;
import java.net.URL;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.oltu.oauth2.common.OAuth;
import org.apache.oltu.oauth2.common.error.OAuthError;
import org.apache.oltu.oauth2.common.exception.OAuthProblemException;
import org.apache.oltu.oauth2.common.exception.OAuthSystemException;
import org.apache.oltu.oauth2.common.message.OAuthResponse;
import org.apache.oltu.oauth2.common.message.types.ParameterStyle;
import org.apache.oltu.oauth2.rs.request.OAuthAccessResourceRequest;
import org.apache.oltu.oauth2.rs.response.OAuthRSResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpStatus;

import com.alibaba.fastjson.JSON;
import com.hm.common.model.ResultMessage;
import com.hm.oauth.def.OauthDef;

/**
 * @author shishun.wang
 * @date 下午6:18:57 2016年8月30日
 * @version 1.0
 * @describe
 */
public class OauthFilter implements Filter {

	private static final Logger logger = LoggerFactory.getLogger(OauthFilter.class);

	@Override
	public void init(FilterConfig filterConfig) throws ServletException {
		System.out.println("过滤器销毁");
	}

	@Override
	public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
			throws IOException, ServletException {
		HttpServletResponse res = (HttpServletResponse) response;
		try {
			OAuthAccessResourceRequest oauthRequest = new OAuthAccessResourceRequest((HttpServletRequest) request,
					ParameterStyle.QUERY);

			String accessToken = oauthRequest.getAccessToken();
			if (!checkAccessToken(accessToken)) {// 认证错误（如果不存在/过期了，返回未验证错误，需重新验证）

			}
			chain.doFilter(request, response);
		} catch (OAuthProblemException e) {
			try {
				oAuthFaileResponse(res);
			} catch (OAuthSystemException ex) {
				logger.debug("error trying to access oauth server :{}", ex);
			}
		} catch (OAuthSystemException e) {
			logger.debug("error trying to access oauth server :{}", e);
		}
	}

	@Override
	public void destroy() {
		System.out.println("过滤器初始化");
	}

	private boolean checkAccessToken(String accessToken) throws IOException {
		URL url = new URL(OauthDef.CHECK_ACCESS_CODE_URL + accessToken);
		HttpURLConnection connection = (HttpURLConnection) url.openConnection();
		connection.setRequestMethod(OauthDef.REQUEST_METHOD);
		connection.disconnect();
		return connection.getResponseCode() == HttpServletResponse.SC_OK;
	}

	private void oAuthFaileResponse(HttpServletResponse res) throws OAuthSystemException, IOException {
		OAuthResponse oauthResponse = OAuthRSResponse.errorResponse(HttpServletResponse.SC_UNAUTHORIZED)
				.setRealm(OauthDef.RESOURCE_SERVER_NAME).setError(OAuthError.ResourceResponse.INVALID_TOKEN)
				.buildHeaderMessage();
		res.setContentType("application/json; charset=utf-8");
		res.addHeader(OAuth.HeaderType.WWW_AUTHENTICATE, oauthResponse.getHeader(OAuth.HeaderType.WWW_AUTHENTICATE));
		PrintWriter writer = res.getWriter();

		ResultMessage<Integer> status = new ResultMessage<Integer>();
		{
			status.setResult(HttpStatus.UNAUTHORIZED.value());
			status.setMessage(OauthDef.INVALID_ACCESS_TOKEN);
		}
		writer.write(JSON.toJSONString(status));
		writer.flush();
		writer.close();
	}
}
